package com.infinit.easyreader.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.infinit.easyreader.entity.Directory;
import com.infinit.easyreader.utils.Consts;

import java.util.ArrayList;
import java.util.List;

/**
 * 类：com.infinit.easyreader.dao.DirectoryDao V[1.0.0]
 * 作用：用于创建和操作Diretory表
 * Created by rzy on 2016/1/31.
 */
public class DirectoryDao extends SQLiteOpenHelper implements Consts {
    private SQLiteDatabase database;
    private String tableName = "directory";

    public DirectoryDao(Context context) {
        super(context, dataBaseName, null, 1);
        database = getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        /**
         * 主要字段说明
         * _id:自增主键
         * path:路径
         * addTime:添加时间
         */


        String sql = "create table directory('_id' INTEGER PRIMARY KEY AUTOINCREMENT," +
                "'path' VARCHAR(50) NOT NULL UNIQUE," +
                "'addTime' VARCHAR(50))";
        /**
         * 创建数据库
         * id:自增主键
         * path:路径 非空
         * name:书名 非空
         *cover:封面图片路径，默认为空
         * isFavorite:收藏标识,默认为否 0：否 1：是
         * lastReadTime:上一次阅读时间
         * dirID:外键 参照directory表的ID字段
         */
        String createBooks = "create table 'books'('_id' INTEGER PRIMARY KEY AUTOINCREMENT," +
                "'path' VARCHAR(50) NOT NULL," +
                "'name' varchar(20) NOT NULL UNIQUE," +
                "'cover' VARCHAR(50)," +
                "'isFavorite' INTEGER DEFAULT 0," +
                "'lastReadTime' VARCHAR(50)," +
                "'dirId' INTEGER," +
                "'lastReadPosition' LARGEINT DEFAULT 0," +
                " FOREIGN KEY(dirId) REFERENCES directory(_id))";


        /**
         * 作用：创建书签表
         * 主要的字段说明：
         * _id:自增主键
         * book_id:书籍的ID，外键
         * position:书籍的定位地址
         */

        String createBookmarks = "CREATE TABLE 'bookmarks'('_id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
                "'book_id' INTEGER NOT NULL," +
                "'position' LARGEINT NOT NULL UNIQUE," +
                "'quote' VARCHAR(100)," +
                "FOREIGN KEY(book_id) REFERENCES books(_id)) ";


        /**
         * 作用：创建排行榜目录表
         * 主要的字段：
         * _id:自增主键
         * ranktype_id:排行类型ID
         * rankName:排行名
         */
        String createRankTypes = "CREATE TABLE 'rankType'('_id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,'ranktype_id' INTEGER NOT NULL,'rankName' VARCHAR(20) NOT NULL UNIQUE )";

        /**
         * 作用：创建排行榜时间表
         * 主要的字段：
         * _id:自增主键
         * rankTimeId:排行时间主键
         * rankTimeName:时间排行名
         */

        String createRankTime = "CREATE TABLE 'rankTime'('_id' INTEGER PRIMARY KEY AUTOINCREMENT ,'rankTimeId' INTEGER NOT NULL,'rankTimeName' VARCHAR(20) NOT NULL UNIQUE )";

        /**
         * 作用：创建排行内容表
         * 主要的字段
         * _id:自增主键
         * contentTypeId:内容的ID
         * contentType:内容的名字
         */


        String createContentType = "CREATE TABLE 'contentType'('_id' INTEGER PRIMARY KEY AUTOINCREMENT,'contentTypeId' INTEGER NOT NULL,'contentType' VARCHAR(20) NOT NULL UNIQUE)";


        db.execSQL(sql);
        db.execSQL(createBooks);
        db.execSQL(createBookmarks);
        db.execSQL(createRankTypes);
        db.execSQL(createRankTime);
        db.execSQL(createContentType);
    }


    /**
     * 作用：获取所有的书籍目录
     *
     * @return 包含所有目录信息的LIST
     */
    public List<Directory> findAll() {
        String[] columns = new String[]{
                "_id",  //0
                "path",   //1
                "addTime" //2
        };
        Cursor cursor = database.query(tableName, columns, null, null, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }
        List<Directory> dirs = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Directory dir = new Directory();
            dir.setId(cursor.getInt(0));
            dir.setPath(cursor.getString(1));
            dir.setAddTime(cursor.getString(2));
            dirs.add(dir);
            cursor.moveToNext();
        }
        cursor.close();
        return dirs;
    }

    /**
     * 作用：通过指定的ID来获取数据库中保存的Directory信息
     *
     * @param id Directory的ID信息
     * @return Directory信息
     */

    public Directory findDirectory(int id) {
        String[] columns = new String[]{
                "_id",  //0
                "path",   //1
                "addTime" //2
        };
        Cursor cursor = database.query(tableName, columns, null, null, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }
        cursor.moveToFirst();
        Directory dir = new Directory();
        dir.setId(cursor.getInt(0));
        dir.setPath(cursor.getString(1));
        dir.setAddTime(cursor.getString(2));
        cursor.close();
        return dir;
    }


    /**
     * 作用：插入一个Directory对象
     *
     * @param dir 需要插入数据库的Directory
     */
    public void insertDirectory(Directory dir) {
        ContentValues values = new ContentValues();
        values.put("path", dir.getPath());
        values.put("addTime", dir.getAddTime());
        database.insertWithOnConflict(tableName, null, values, SQLiteDatabase.CONFLICT_IGNORE);
    }

    /**
     * 作用：删除一个指定的Dirctory
     *
     * @param dir 指定的Dir
     */


    public void deleteDir(Directory dir) {
        String whereClause = "_id = ?";
        String[] whereArgs = new String[]{

                dir.getId() + ""
        };


        database.delete(tableName, whereClause, whereArgs);


    }

    /**
     * 作用：更新指定的Dir
     *
     * @param dir Directory对象
     */

    public void updateDir(Directory dir) {
        ContentValues values = new ContentValues();
        values.put("path", dir.getPath());
        values.put("addTime", dir.getAddTime());
        database.update(tableName, values, "_id=?", new String[]{dir.getId() + ""});
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


    }

    public void finish() {
        database.close();
    }

}
